//导入数据库模块
const db = require('../db/index.js')


//查询
exports.searchKey = (req, res) => {
    const key = req.query.key;
    console.log(key);

    // 创建两个查询的Promise
    const carsPromise = new Promise((resolve, reject) => {
        db.query('SELECT * FROM cars WHERE name LIKE ?', [`%${key}%`], (err, results) => {
            if (err) {
                return reject(err);
            }
            resolve(results);
        });
    });

    const articlesPromise = new Promise((resolve, reject) => {
        db.query('SELECT * FROM article WHERE title LIKE ?', [`%${key}%`], (err, results) => {
            if (err) {
                return reject(err);
            }
            resolve(results);
        });
    });

    // 使用Promise.all来等待所有查询完成
    Promise.all([carsPromise, articlesPromise])
        .then(results => {
            // 当两个查询都完成时，发送结果
            res.send({ cars: results[0], articles: results[1] });
        })
        .catch(err => {
            // 处理查询中的任何错误
            console.error(err);
            res.status(500).send('数据库查询失败');
        });
};
